package net.neptech.service.impl;

import net.neptech.finalClass.SessionConstants;
import net.neptech.model.ipc.SensitiveWord;
import net.neptech.repository.SensitiveWordRepository;
import net.neptech.service.RedisService;
import net.neptech.service.SensitiveWordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;

/**
 * @Author HuangZhengmin
 * @desc  敏感词服务实现类
 * @Date 2025/8/19 20:35
 * @Version 1.0
 */
@Service
public class SensitiveWordServiceImpl implements SensitiveWordService {

  @Autowired
  private RedisService redisService;

  @Autowired
  private SensitiveWordRepository sensitiveWordRepository;

  @Override
  public void initSensitiveWords() {
    // 从数据库加载所有敏感词
    List<SensitiveWord> sensitiveWords = sensitiveWordRepository.findAll();

    // 清空Redis中的现有敏感词
    clearAllSensitiveWords();

    // 将数据库中的敏感词添加到Redis
    for (SensitiveWord sensitiveWord : sensitiveWords) {
      addSensitiveWordToRedis(sensitiveWord.getWord(), sensitiveWord.getCategory());
    }
  }

  @Override
  /**
   * 检查内容是否包含敏感词
   * @param content 需要检查的内容字符串
   * @return 如果包含敏感词返回true，否则返回false
   */
  public boolean containsSensitiveWords(String content) {
    // 检查内容是否为空或空白字符串
    if (!StringUtils.hasText(content)) {
      return false;
    }

    // 从Redis缓存中获取敏感词集合
    Set<String> sensitiveWords = redisService.getCacheSet(SessionConstants.SENSITIVE_WORDS_KEY);

    // 如果缓存中没有敏感词或集合为空，则从数据库初始化敏感词
    if (sensitiveWords == null || sensitiveWords.isEmpty()) {
      initSensitiveWords();
      // 重新从Redis获取敏感词集合
      sensitiveWords = redisService.getCacheSet(SessionConstants.SENSITIVE_WORDS_KEY);

      // 如果数据库也没有敏感词，直接返回false
      if (sensitiveWords == null || sensitiveWords.isEmpty()) {
        return false;
      }
    }

    // 遍历敏感词集合，检查内容中是否包含敏感词
    for (String word : sensitiveWords) {
      // 从 "category:word" 格式中提取实际的敏感词
      String actualWord = word.substring(word.indexOf(":") + 1);
      // 使用正则表达式进行不区分大小写的匹配，如果找到敏感词则返回true
      if (Pattern.compile(Pattern.quote(actualWord), Pattern.CASE_INSENSITIVE)
              .matcher(content).find()) {
        return true;
      }
    }
    // 遍历完所有敏感词都没有匹配，返回false
    return false;
  }

  @Override
  public void addSensitiveWord(String word, String category) {
    if (StringUtils.hasText(word)) {
      // 1. 保存到数据库
      SensitiveWord sensitiveWord = new SensitiveWord();
      sensitiveWord.setWord(word);
      sensitiveWord.setCategory(category);
      sensitiveWord.setCreatedAt(java.time.LocalDateTime.now());
      sensitiveWordRepository.save(sensitiveWord);

      // 2. 添加到Redis缓存
      addSensitiveWordToRedis(word, category);
    }
  }

  /**
   * 添加敏感词到Redis缓存（内部方法）
   * @param word 敏感词
   * @param category 分类
   */
  private void addSensitiveWordToRedis(String word, String category) {
    if (StringUtils.hasText(word)) {
      // 存储格式: "category:word"
      String value = category + ":" + word;
      // 使用 RedisService 的 setCacheSet 方法添加敏感词
      Set<String> currentSet = redisService.getCacheSet(SessionConstants.SENSITIVE_WORDS_KEY);
      if (currentSet == null) {
        currentSet = new HashSet<>();
      }
      currentSet.add(value);
      redisService.setCacheSet(SessionConstants.SENSITIVE_WORDS_KEY, currentSet);
    }
  }

  @Override
  public void removeSensitiveWord(String word) {
    if (StringUtils.hasText(word)) {
      // 1. 从数据库删除
      List<SensitiveWord> wordsToDelete = sensitiveWordRepository.findByWord(word);
      sensitiveWordRepository.deleteAll(wordsToDelete);

      // 2. 从Redis缓存删除
      removeSensitiveWordFromRedis(word);
    }
  }

  /**
   * 从Redis缓存删除敏感词（内部方法）
   * @param word 敏感词
   */
  private void removeSensitiveWordFromRedis(String word) {
    // 移除所有包含该词的记录
    Set<String> sensitiveWords = redisService.getCacheSet(SessionConstants.SENSITIVE_WORDS_KEY);
    if (sensitiveWords != null && !sensitiveWords.isEmpty()) {
      Set<String> wordsToRemove = new HashSet<>();
      for (String w : sensitiveWords) {
        if (w.endsWith(":" + word)) {
          wordsToRemove.add(w);
        }
      }
      // 创建新的集合，移除需要删除的敏感词
      Set<String> updatedSet = new HashSet<>(sensitiveWords);
      updatedSet.removeAll(wordsToRemove);
      // 更新 Redis 中的集合
      redisService.setCacheSet(SessionConstants.SENSITIVE_WORDS_KEY, updatedSet);
    }
  }

  /**
   * 清空所有敏感词（从数据库和Redis）
   */
  public void clearAllSensitiveWords() {
    // 清空数据库
    sensitiveWordRepository.deleteAll();
    // 清空Redis
    redisService.deleteObject(SessionConstants.SENSITIVE_WORDS_KEY);
  }


}